package stripepay

import (
	"context"
	"simplifly-tech/payment/internal"
	model2 "simplifly-tech/payment/model"
	"simplifly-tech/utility/log"
	"strconv"

	"github.com/shopspring/decimal"
	"github.com/stripe/stripe-go/v80"
	"github.com/stripe/stripe-go/v80/customer"
	"github.com/stripe/stripe-go/v80/paymentintent"
)

func (stripeService *StripeService) Pay(ctx context.Context, payData *model2.PayData) (*model2.PaymentResponse, error) {

	//var fee decimal.Decimal
	//var err error
	//if stripeService.FeeCurrency != "" && stripeService.Fee != decimal.Zero {
	//	fee, err = rate.Convert(context.TODO(), stripeService.FeeCurrency, fee, paymentData.Currency)
	//	if err != nil {
	//		return nil, err
	//	}
	//}
	//err, sysIncome := dto.CreateIncomeByPayment(paymentData, stripeService.TransactionRate, fee)
	//if err != nil {
	//	return nil, err
	//}
	//paymentNotification := internal.PaymentNotification{
	//	Status:       consts.NotifyStatusSuccess,
	//	OrderID:      payData.YeepayData.PayChannel,
	//	IncomeID:     payData.IncomeID,
	//	AsyncPayment: true,
	//}
	respData, err := stripeService.getPayConfig(payData) //获取支付需要的config 需要的ClientSecret
	if err != nil {
		return nil, err
	}

	return &model2.PaymentResponse{
		OrderID:      payData.OrderID,
		StripPayData: respData,
	}, nil
}

func (stripeService *StripeService) getPayConfig(payData *model2.PayData) (*internal.StripePayRespData, error) {
	moneyFrom := payData.Amount.Mul(decimal.NewFromFloat(100))
	money := moneyFrom.IntPart()
	stripe.Key = stripeService.SecretKey
	customerParams := &stripe.CustomerParams{
		PreferredLocales: stripe.StringSlice([]string{"en"}),
	}
	c, errs := customer.New(customerParams)
	if errs != nil {
		return nil, errs
	}

	paymentIntentParams := &stripe.PaymentIntentParams{
		Amount:      stripe.Int64(money),
		Currency:    stripe.String(payData.Currency),
		Customer:    stripe.String(c.ID),
		Description: &payData.Body,
		PaymentMethodTypes: stripe.StringSlice([]string{
			"card",
		}),
		Metadata: map[string]string{
			"order_id":  payData.OrderID,                     // 可选的元数据
			"income_id": strconv.Itoa(int(payData.IncomeID)), // 可选的元数据
		},
	}
	paymentIntentParams.AddMetadata("return_url", payData.ReturnUrl) // 用户支付后将被重定向到此 URL

	intent, err := paymentintent.New(paymentIntentParams)
	if err != nil {
		log.Errorf("Error creating payment intent: %v", err)
		return nil, err
	}

	stripePayRespData := internal.StripePayRespData{
		PublicKey:    stripeService.PublicKey,
		ClientSecret: intent.ClientSecret,
		ReferenceID:  intent.ID,
	}
	return &stripePayRespData, nil

}

func (stripeService *StripeService) CancelPay(tx context.Context, paymentID string) error {
	return nil
}
